package com.zt.consumer;

import com.alibaba.fastjson.JSON;
import com.zt.es.GoodsVo;
import com.zt.mapper.GoodsMapper;
import com.zt.pojo.Goods;
import lombok.SneakyThrows;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.BeanUtils;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author: 王佳祥
 * @Date: 2024 09 04 11:48
 */
@Component
public class EsIndex {
    @Resource
    private RestHighLevelClient restHighLevelClient;

    @Resource
    private GoodsMapper mapper;
    @SneakyThrows
    @KafkaListener(topics = "Instantly")
    public void esCreateIndex(String msg){
//      1.修改状态存到数据库
        Goods goods = JSON.parseObject(msg, Goods.class);
        GoodsVo goodsVo = new GoodsVo();
        goods.setApSatus(0);
        mapper.updateById(goods);
        Goods goods1 = mapper.selectById(goods);
        BeanUtils.copyProperties(goods1,goodsVo);

//        2.存入es中
        IndexRequest indexRequest = new IndexRequest("zk3_test");

        indexRequest.id(goodsVo.getId().toString());

        indexRequest.source(JSON.toJSONString(goodsVo), XContentType.JSON);


        restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
    }
}


